package com.belizer.demo.thread;

public class Demo9 {

    private static class ThisEscape{

        //可能会提前暴漏当前对象
        public ThisEscape(EventSource source) {
            source.registerListener(
                    new EventListener() {
                        public void onEvent(Event e) {
                            doSomething(e);
                        }


                    });
        }

        private void doSomething(Event e) {
            //todo ...
        }
    }

    private static class SafeListener {
        private final EventListener listener;
        //构造私有，创建一个工厂方法，防止提前暴漏当前对象
        private SafeListener () {
            listener = new EventListener() {
                @Override
                public void onEvent(Event e) {
                    doSomething(e);
                }
            };
        }

        public static SafeListener newInstance(EventSource source) {
            SafeListener safe = new SafeListener();
            source.registerListener(safe.listener);
            return safe;
        }


        private void doSomething(Event e) {
            //todo ...
        }
    }

    private  interface EventSource {
        void registerListener(EventListener listener);
    }

    private  interface EventListener{
        void onEvent(Event e);
    }

    private  interface  Event{

    }


}
